#!/usr/bin/env python3

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

# cv.imshow("img", img)
# cv.imshow("img_template", img_template)

img = cv.imread('../pic/7.png', 0)
img2 = img.copy()
template = cv.imread('../pic/7_little_cat.png', 0)
# shape的返回值是height weight，-1可以将参数颠倒顺序  黑白图像仅两个参数
w, h = template.shape[::-1]
# 列表中所有的6种比较方法
methods = ['cv.TM_CCOEFF', 'cv.TM_CCOEFF_NORMED', 'cv.TM_CCORR',
           'cv.TM_CCORR_NORMED', 'cv.TM_SQDIFF', 'cv.TM_SQDIFF_NORMED']

for meth in methods:
    img = img2.copy()
    # eval函数会执行内部参数，并返回结果，谨慎使用要执行的命令
    # 此处返回的是具体的数字
    method = eval(meth)
    # 应用模板匹配
    res = cv.matchTemplate(img, template, method)
    # minMaxLoc函数 只返回一个坐标min_loc[0],[1]表示y
    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(res)
    # 如果方法是TM_SQDIFF或TM_SQDIFF_NORMED，则取最小值
    if method in [cv.TM_SQDIFF, cv.TM_SQDIFF_NORMED]:
        top_left = min_loc
    else:
        top_left = max_loc

    bottom_right = (top_left[0] + w, top_left[1] + h)
    cv.rectangle(img, top_left, bottom_right, (0, 0, 255), 2)
    plt.subplot(121), plt.imshow(res, cmap='gray')
    plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
    plt.subplot(122), plt.imshow(img, cmap='gray')
    plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
    plt.suptitle(meth)
    plt.show()

